import { http } from '@/utils/http'
export default {
  data() {
    return {
      scrollTop: -1,
      loadStatus: "loading",
      refreshStatus: false, // 下拉刷新状态
      pageNumber: 1,
      queryParam: {},
      objectField: {},
      dataSource: [],
    };
  },
  methods: {
    // 下拉刷新(重置刷新)
    resetRefresh(pullDown = false) {
      this.pageNumber = 1;
      if (pullDown) {
        this.refreshStatus = true;
      }
      this.loadData(1);
    },
    // 上拉加载
    reachBottom() {
      // nomore 直接返回
      if (this.loadStatus == "nomore") return;
      this.loadStatus = "loading";
      this.loadData();
    },
    // 到顶部
    goTop(e) {
      this.scrollTop = -1;
      this.$nextTick(() => {
        this.scrollTop = 0;
      });
    },
    loadData(arg) {
      if (!this.apiMethods.list) {
        uni.showToast({
          icon: "none",
          title: "请设置apiMethods.list属性!",
        });
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.pageNumber = 1;
      }
      var params = this.getQueryParams(); //查询条件
      // 调列表方法
      http({
        method: 'POST',
        url: this.apiMethods.list,
        data: params,
      }).then((res) => {
        if (res.code == 200) {
          const { data, totalPage, objectField } = res.result;
          this.objectField = objectField;
          // 第一页list替换，否则追加
          if (this.pageNumber == 1) {
            this.dataSource = [];
            this.dataSource = data;
            this.loadStatus = "loading";
            // 到顶部
            this.goTop();
            this.refreshStatus = false;
            this.waitRefresh = false;
          } else {
            this.dataSource = [...this.dataSource, ...data];
          }
          // 最后一条判断
          if (this.pageNumber >= totalPage) {
            this.loadStatus = "nomore";
          } else {
            this.pageNumber++;
          }
          this.dealListResult(this.dataSource);
        } else {
          uni.showToast({
            icon: "none",
            title: res.message,
          });
        }
      });
    },
    dealListResult(dataSource) {
      if (dataSource.length) {
        this.dataSource = dataSource;
      } else {
        this.dataSource = [];
      }
    },
    getQueryParams() {
      var param = Object.assign(this.queryParam);
      param.pageNumber = this.pageNumber;
      return param;
    },
  },
};
